package vn.khanhhoi;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

public class RenderToString {

    public String renderViewToString(ModelMap map, HttpServletRequest request, HttpServletResponse httpServletResponse, final String viewName, final ViewResolver viewResolver) {
        final StringWriter html = new StringWriter();
        View pdfView = new View() {
            @Override
            public String getContentType() {
                return "application/pdf";
            }

            @Override
            public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

                HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response) {
                    @Override
                    public PrintWriter getWriter() throws IOException {
                        return new PrintWriter(html);
                    }
                };
                View realView = viewResolver.resolveViewName(viewName, Locale.US);
                Map<String, Object> newModel = new HashMap<String, Object>(model);
                newModel.put("pdfMode", Boolean.TRUE);
                realView.render(newModel, request, wrapper);
            }
        };
        try {
            pdfView.render(map, request, httpServletResponse);
        } catch (Exception e) {
            // Ignored for now
        }
        return html.toString();
        //return Utility.EncodeHtml(html.toString());
    }
}
